import { PlusCircleOutlined } from "@ant-design/icons";
import {
  message,
  Spin,
  Tooltip,
  Empty,
  Button,
  Modal,
  Tag,
  Popconfirm,
} from "antd";
import dayjs from "dayjs";
import { FC, useEffect, useRef, useState } from "react";
import styles from "../styles.less";
import Https from "@/utils/Https";
import { history } from "umi";
import {
  getRoomStyle,
  secondsList,
  weekNameList,
} from "@/pages/course/interface";
import {
  ProForm,
  ProFormText,
  ProFormTextArea,
} from "@ant-design/pro-components";
import { courseTypeList } from "../configFile";
const RoomCourse: FC<any> = (props) => {
  const { addWork, venueObj, sortReload, weekTimeInfo, isFull } = props;
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [scrollTop, setScrollTop] = useState(0);
  const [scrollLeft, setScrollLeft] = useState(0);
  const [RoomData, setRoomData] = useState([]);
  const [windowHeigth, setWindowHeight] = useState(window.innerHeight);
  const XData = ["", ...secondsList];
  const formRef = useRef();
  //获取排课表数据
  const getData = async (venueId, date) => {
    let params = {
      venueId,
      date,
    };
    setLoading(true);
    let res = await Https.get(
      "/classRoomOccupancy/classRoomOccupancyList",
      params,
      true
    );
    setLoading(false);
    if (res.code == 200 && res.data) {
      if (res.data.length > 0) {
        setRoomData(res.data);
      } else {
        setRoomData([]);
      }
    } else {
      setRoomData([]);
      message.error(res.msg);
    }
  };
  //删除记录
  const deleteItem = async (ids) => {
    setLoading(true);
    let res = await Https.post("/classRoomOccupancy/delete", ids, true);
    setLoading(false);
    if (res.code == 200) {
      message.success("操作成功");
      getData(venueObj.id, weekTimeInfo.date);
    } else {
      message.error(res.msg);
    }
  };
  useEffect(() => {
    if (venueObj.id && weekTimeInfo.date) {
      getData(venueObj.id, weekTimeInfo.date);
    }
  }, [venueObj, weekTimeInfo, sortReload]);
  const handleResize = () => {
    setWindowHeight(window.innerHeight);
  };
  useEffect(() => {
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
  return (
    <Spin spinning={loading}>
      {RoomData && RoomData.length > 0 ? (
        <div
          className={styles.timaMain}
          onScroll={(e) => {
            let { scrollTop } = e.target;
            setScrollTop(scrollTop);
          }}
          style={{ height: isFull ? windowHeigth - 90 + "px" : "500px" }}
        >
          <div className={styles.boxHidden}>
            <div className={styles.timeContent}>
              {XData.map((e, index) => (
                <div
                  key={index}
                  className={`${styles.timeHr} ${
                    index == 0 ? styles.strik : ""
                  } ${index == 0 && scrollTop > 60 ? styles.strikShadow : ""}`}
                >
                  {index == 0 ? (
                    <>
                      <div
                        className={styles.timeSecond}
                        style={{ zIndex: 100, lineHeight: "59px" }}
                      >
                        时间段
                      </div>
                      <div
                        className={styles.timeHeaderOther}
                        style={{ marginLeft: -scrollLeft + "px" }}
                      >
                        {RoomData &&
                          RoomData.length > 0 &&
                          RoomData.map((item, index) => (
                            <div className={styles.timeHeaderName}>
                              <span
                                className={styles.roomSpan}
                                title={item.classRoomName}
                              >
                                {item.classRoomName}
                              </span>
                              {item.roomStatus == "0" &&
                              weekTimeInfo.isRest == "0" ? (
                                <PlusCircleOutlined
                                  onClick={() => {
                                    addWork("add", item, "新建占用");
                                  }}
                                  style={{
                                    marginLeft: "5px",
                                    color: "#1677ff",
                                  }}
                                />
                              ) : (
                                <Tooltip title="教室禁用或场馆当天放假">
                                  <PlusCircleOutlined
                                    style={{
                                      marginLeft: "5px",
                                      color: "#999999",
                                    }}
                                  />
                                </Tooltip>
                              )}
                            </div>
                          ))}
                      </div>
                    </>
                  ) : (
                    <div className={styles.timeSecond}>{e}</div>
                  )}
                </div>
              ))}
            </div>
            <div
              className={styles.roomContent}
              onScroll={(e) => {
                let { scrollLeft } = e.target;
                setScrollLeft(scrollLeft);
              }}
            >
              <div className={styles.roomContentBox}>
                {RoomData &&
                  RoomData.length > 0 &&
                  RoomData.map((item, index) => (
                    <div className={styles.roomContentItem}>
                      <div className={styles.roomHeader}></div>
                      {item.list &&
                        item.list.length > 0 &&
                        item.list.map((c, cindex) => (
                          <div
                            className={`${styles.card_resize} ${
                              c.status == 2 ? styles.hasExpired : ""
                            }`}
                            style={
                              getRoomStyle({ ...c, colour: "#02a7f0" }).objStyle
                            }
                            onClick={() => {
                              if (c.status == 2) {
                                return;
                              }
                              if (c.occupiedType != 4) {
                                let classTime =
                                  dayjs(c.startTimeSlot).format("HH:mm") +
                                  "~" +
                                  dayjs(c.endTimeSlot).format("HH:mm");
                                setOpen(true);
                                setLoading(true);
                                formRef?.current?.resetFields();
                                setTimeout(() => {
                                  formRef?.current?.setFieldsValue({
                                    classRoomName: item.classRoomName,
                                    classDate:
                                      dayjs(c.startTimeSlot).format(
                                        "YYYY-MM-DD"
                                      ) +
                                      "(" +
                                      weekNameList[
                                        dayjs(c.startTimeSlot).day() == 0
                                          ? 7
                                          : dayjs(c.startTimeSlot).day()
                                      ] +
                                      ")",
                                    classTime,
                                    remark: c.remark,
                                  });
                                  setLoading(false);
                                }, 500);
                              } else {
                                addWork(
                                  "edit",
                                  { ...c, classRoomName: item.classRoomName },
                                  "编辑占用"
                                );
                              }
                            }}
                          >
                            {c.status == 2 && (
                              <div className={styles.card_operate}>
                                <Popconfirm
                                  title="确定要删除这条记录吗?"
                                  onConfirm={() => {
                                    setOpen(false);
                                    deleteItem([c.id]);
                                  }}
                                >
                                  <a style={{ color: "red" }}>删除</a>
                                </Popconfirm>
                              </div>
                            )}
                            <div className={styles.card_item}>
                              {dayjs(c.startTimeSlot).format("HH:mm")}~
                              {dayjs(c.endTimeSlot).format("HH:mm")}(
                              {c.status == 1 ? "已占用" : "已完成"})
                              <Tag>{courseTypeList[c.occupiedType]}</Tag>
                            </div>
                            <div
                              className={styles.card_name}
                              style={{ marginTop: "10px" }}
                            >
                              {c.remark}
                            </div>
                          </div>
                        ))}
                    </div>
                  ))}
              </div>
            </div>
          </div>
        </div>
      ) : (
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={
            <div>
              当前场馆下暂无关联教室 <br />
              <Button
                style={{ marginTop: "10px" }}
                type="primary"
                onClick={() => {
                  history.push("/stadium/classroom");
                }}
              >
                去创建教室并且关联到{venueObj.venueName}
              </Button>
            </div>
          }
        />
      )}
      <Modal
        title="详情"
        onCancel={() => {
          setOpen(false);
        }}
        width="40%"
        open={open}
        footer={null}
      >
        <Spin spinning={loading}>
          <ProForm
            formRef={formRef}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 16 }}
            submitter={false}
            readonly
            layout="horizontal"
          >
            <ProFormText name="classRoomName" label="教室名" />
            <ProFormText name="classDate" label="占用日期" />
            <ProFormText name="classTime" label="占用时间" />
            <ProFormTextArea name="remark" label="占用原因" />
          </ProForm>
        </Spin>
      </Modal>
    </Spin>
  );
};
export default RoomCourse;
